﻿Imports System.Data.Common

Public Class Graph
    Inherits System.Web.UI.Page

    Private Enum enumChartType
        TimeSeries
        Column
        DepthProfile
    End Enum

    Private Property ChartType As enumChartType
        Get
            Return cboChartType.SelectedIndex
        End Get
        Set(value As enumChartType)
            cboChartType.SelectedIndex = value
            Select Case ChartType
                Case enumChartType.TimeSeries, enumChartType.Column
                    btnAddLeft.Text = "< " & GetLocalResourceObject("btnAddLeftResource1.Text")
                    btnAddRight.Visible = True
                Case enumChartType.DepthProfile
                    btnAddLeft.Text = GetLocalResourceObject("btnAddLeftResource1.Text")
                    btnAddRight.Visible = False
            End Select

            If GraphSettings Is Nothing Then Response.Redirect("Configure.aspx") 'if session terminates or website restarts; goto configure screen

            With GraphSettings
                .Clear()
                FillSeriesList()
                .ChartType = value
                .Save()
            End With
            FillStationList()
            RenderChart()
        End Set
    End Property

    Private Enum enumChartSize
        Small
        Medium
        Large
    End Enum

    Private Enum enumCalcType
        None
        MovingAvg
        CriteriaLimits
    End Enum

    Private Class clsSeries
        Friend Name As String = ""
        Friend StationID As String = ""
        Friend PCode As String = ""
        Friend DateTime As String = ""
        Friend AxisType As DataVisualization.Charting.AxisType = DataVisualization.Charting.AxisType.Primary
        Friend CalcType As enumCalcType = enumCalcType.None
        Friend CalcVal As Double = 0 'number of values in moving avg or criteria limits
        Friend CalcSource As String = "" 'name of source series
    End Class

    Private Class clsGraphSettings
        Friend lstSeries As New List(Of clsSeries)
        Friend Title As String = ""
        Friend IsLogarithmicPrimary = False
        Friend IsLogarithmicSecondary = False
        Friend ShowValueLabels = False
        Friend ChartType As enumChartType = enumChartType.TimeSeries
        Friend ChartSize As enumChartSize = enumChartSize.Medium
        Friend Zoom As Double = 0.0
        Friend Pan As Double = 0.0
        Friend UnitsPerPixel As Double = 0.0
        Friend Sub Clear()
            lstSeries.Clear()
            Title = ""
            IsLogarithmicPrimary = False
            IsLogarithmicSecondary = False
            Zoom = 0.0
            Pan = 0.0
            ShowValueLabels = False
            Save()
        End Sub
        Friend Sub Save()
            HttpContext.Current.Session("GraphSettings") = Me
        End Sub
    End Class

    Private GraphSettings As clsGraphSettings
    'Shared GraphSettings As clsGraphSettings

    Private ChartSizes() As Drawing.Size = {New Drawing.Size(640, 300),
                                            New Drawing.Size(960, 500),
                                            New Drawing.Size(960, 700)}

    Protected Overrides Sub InitializeCulture()
        With ProjectSettings
            System.Threading.Thread.CurrentThread.CurrentUICulture = .Language
            System.Threading.Thread.CurrentThread.CurrentCulture = .Language
        End With

        MyBase.InitializeCulture()
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'retrieve previous settings
        GraphSettings = Session("GraphSettings")

        If Not IsPostBack Then

            If GraphSettings Is Nothing Then GraphSettings = New clsGraphSettings
            btnAddLeft.Text = "< " & GetLocalResourceObject("btnAddLeftResource1.Text")

            ChartType = GraphSettings.ChartType

            CheckSelectedData()  'if have not previously selected data, this will redirect you
            lblInfo.Text = String.Format(lblInfo.Text, NumSelectedRecords)

            'was unable to get redirect from map to work without session being reset
            'With ProjectSettings
            '    If .GraphStation <> "" And .GraphPCode <> "" Then
            '        cboStationID.Text = .GraphStation
            '        FillPCodeList()
            '        cboPCode.Text = .GraphPCode
            '        'clear these global settings
            '        .GraphStation = ""
            '        .GraphPCode = ""
            '    End If
            'End With
            RenderChart() 'so will at least have properly sized empty chart
        End If

    End Sub

    Private Sub cboChartType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChartType.SelectedIndexChanged
        ChartType = cboChartType.SelectedIndex
        chkLogAxisPrimary.Visible = ChartType <> enumChartType.Column
        chkLogAxisSecondary.Visible = ChartType = enumChartType.TimeSeries
    End Sub

    Private Sub FillStationList()
        Dim dt As DataTable = SelectedDataTable
        If dt Is Nothing Then Exit Sub

        Dim sql As String = ""
        Select Case ChartType
            Case enumChartType.DepthProfile
                sql = "Station_ID IS NOT NULL AND PCode IS NOT NULL AND Date_Time IS NOT NULL AND Result IS NOT NULL AND Depth_M IS NOT NULL"
            Case enumChartType.TimeSeries, enumChartType.Column
                sql = "Station_ID IS NOT NULL AND PCode IS NOT NULL AND Date_Time IS NOT NULL AND Result IS NOT NULL"
        End Select

        cboStationID.Items.Clear()
        cboStationID.Items.Add(String.Format("({0})", GetGlobalResourceObject("WRDB", "AllStations")))

        Dim datarows() As DataRow = dt.Select(sql, "Station_ID")
        If datarows.Length = 0 Then Exit Sub
        For Each dr As DataRow In datarows.CopyToDataTable.DefaultView.ToTable(True, {"Station_ID"}).Rows
            'add StationID - StationName to list
            Dim StaID As String = dr(0)
            Dim datarowsStation() As DataRow = ProjectDataset.Tables("Stations").Select(String.Format("Station_ID = '{0}'", StaID), "Station_Name")
            Dim StaName As String = "Unknown"
            If datarowsStation.Length = 1 Then
                StaName = TestNull(datarowsStation(0)("Station_Name"), "")
            End If
            cboStationID.Items.Add(StaID & " - " & StaName)
        Next

        FillPCodeList()
    End Sub

    Private Sub FillSeriesList()
        lstCalc.Items.Clear()
        lstDelete.Items.Clear()
        If GraphSettings Is Nothing Then Response.Redirect("Configure.aspx") 'if session terminates or website restarts; goto configure screen
        For Each ser As clsSeries In GraphSettings.lstSeries
            If ser.CalcType = enumCalcType.None Then lstCalc.Items.Add(ser.Name)
            lstDelete.Items.Add(ser.Name)
        Next
        If lstCalc.Items.Count > 0 Then lstCalc.SelectedIndex = 0
        If lstCalcType.Items.Count > 0 Then lstCalcType.SelectedIndex = 0
    End Sub

    Private Sub cboStationID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboStationID.SelectedIndexChanged
        FillPCodeList()
    End Sub

    Private Sub FillPCodeList()
        Dim prevPCode As String = cboPCode.Text
        Dim dt As DataTable = SelectedDataTable
        If dt Is Nothing Then Exit Sub

        Dim sql As String = ""
        If cboStationID.SelectedIndex > 0 Then
            sql = String.Format("Station_ID='{0}' AND ", StringSplit(cboStationID.Text, " - ")(0))
        End If
        Select Case ChartType
            Case enumChartType.DepthProfile
                sql &= "PCode IS NOT NULL AND Date_Time IS NOT NULL AND Result IS NOT NULL AND Depth_M IS NOT NULL"
            Case enumChartType.TimeSeries, enumChartType.Column

                sql &= "PCode IS NOT NULL AND Date_Time IS NOT NULL AND Result IS NOT NULL"
        End Select
        cboPCode.Items.Clear()
        cboPCode.Items.Add(String.Format("({0})", GetGlobalResourceObject("WRDB", "AllPCodes")))
        Dim selRows As DataRow() = dt.Select(sql, "PCode")
        If selRows IsNot Nothing Then
            For Each dr As DataRow In selRows.CopyToDataTable.DefaultView.ToTable(True, {"PCode"}).Rows
                'add PCode - AnalName to list
                Dim PCode As String = dr(0)
                Dim datarowsAnal() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode = '{0}'", PCode), "PCode")
                Dim AnalName As String = "Unknown"
                If datarowsAnal.Length = 1 Then
                    AnalName = TestNull(datarowsAnal(0)("Anal_Name"), "")
                End If
                cboPCode.Items.Add(PCode & " - " & AnalName)
            Next
        End If
        If cboPCode.Items.FindByText(prevPCode) IsNot Nothing Then cboPCode.Text = prevPCode
        FillDateList()
    End Sub

    Private Sub cboPCode_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPCode.SelectedIndexChanged
        FillDateList()
    End Sub

    Private Sub FillDateList()
        Select Case ChartType
            Case enumChartType.DepthProfile
                Dim prevDate As String = cboDate.Text
                Dim dt As DataTable = SelectedDataTable
                If dt Is Nothing Then Exit Sub
                Dim staFilter As String = String.Format("Station_ID='{0}' AND ", StringSplit(cboStationID.Text, " - ")(0))
                If cboStationID.SelectedIndex = 0 Then staFilter = ""
                Dim pcodeFilter As String = String.Format("PCode='{0}' AND ", StringSplit(cboPCode.Text, " - ")(0))
                If cboPCode.SelectedIndex = 0 Then pcodeFilter = ""
                Dim sql As String = String.Format("{0}{1} Date_Time IS NOT NULL AND Depth_M IS NOT NULL", staFilter, pcodeFilter)
                cboDate.Items.Clear()
                cboDate.Items.Add(String.Format("({0})", GetGlobalResourceObject("WRDB", "AllDates")))
                For Each dr As DataRow In dt.Select(sql, "Date_Time").CopyToDataTable.DefaultView.ToTable(True, {"Date_Time"}).Rows
                    cboDate.Items.Add(String.Format("{0:g}", dr(0)))
                Next
                lblDate.Visible = True
                cboDate.Visible = True
                cboDate.Width = New Unit(8, UnitType.Em)
                If cboDate.Items.FindByText(prevDate) IsNot Nothing Then cboDate.Text = prevDate
            Case enumChartType.TimeSeries, enumChartType.Column
                lblDate.Visible = False
                cboDate.Visible = False
        End Select
    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAddLeft.Click, btnAddRight.Click
        Dim lstSta As New List(Of String), lstPCode As New List(Of String), lstDate As New List(Of String)
        For i As Integer = 1 To 3
            Dim lst As List(Of String) = Choose(i, lstSta, lstPCode, lstDate)
            Dim cbo As DropDownList = Choose(i, cboStationID, cboPCode, cboDate)
            If cbo.SelectedIndex > 0 Then
                lst.Add(StringSplit(cbo.Text, " - ")(0))
            Else
                For j As Integer = 1 To cbo.Items.Count - 1
                    lst.Add(StringSplit(cbo.Items(j).Text, " - ")(0))
                Next
            End If
        Next
        If ChartType <> enumChartType.DepthProfile Then 'there will be no dates in list; just put in dummy value so will loop correctly
            lstDate.Add("")
        End If

        If GraphSettings Is Nothing Then Response.Redirect("Configure.aspx") 'if session terminates or website restarts; goto configure screen

        With GraphSettings
            For Each sta As String In lstSta
                For Each pcode As String In lstPCode
                    For Each dt As String In lstDate
                        Dim seriesName As String = ""
                        If ChartType = enumChartType.DepthProfile Then
                            seriesName = String.Format("{0} {3} {1} ({2})", pcode, sta, dt, GetGlobalResourceObject("WRDB", "at"))
                        Else
                            seriesName = String.Format("{0} {2} {1}", pcode, sta, GetGlobalResourceObject("WRDB", "at"))
                        End If
                        'don't add if already exists
                        For Each ser As clsSeries In .lstSeries
                            If ser.Name = seriesName Then
                                RenderChart()
                                Exit Sub
                            End If
                        Next
                        .lstSeries.Add(New clsSeries With {.Name = seriesName,
                                                            .StationID = sta,
                                                            .PCode = pcode,
                                                            .DateTime = dt,
                                                            .AxisType = IIf(sender Is btnAddLeft, DataVisualization.Charting.AxisType.Primary,
                                                                                                    DataVisualization.Charting.AxisType.Secondary)})
                    Next
                Next
            Next
            .Zoom = 0.0
            .Pan = 0.0
            .Save()
        End With
        RenderChart()
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        If GraphSettings Is Nothing Then Response.Redirect("Configure.aspx") 'if session terminates or website restarts; goto configure screen
        GraphSettings.Clear()
        FillSeriesList()
        RenderChart()
    End Sub

    ''' <summary>
    ''' This forces chart to be rendered during partial update
    ''' </summary>
    Private Sub Chart1_Load(sender As Object, e As EventArgs) Handles Chart1.Load
        If Chart1.Visible Then RenderChart()
    End Sub

    Private Sub RenderChart()

        If GraphSettings Is Nothing Then Response.Redirect("Configure.aspx") 'if session terminates or website restarts; goto configure screen

        With GraphSettings
            If Val(hdnMouseWheel.Value) <> 0 Then GraphSettings.Zoom += 0.1 * Val(hdnMouseWheel.Value)
            'for time series and rainfall, will pan on x axis, for profile on y axis
            If hdnPan.Value.Contains(",") AndAlso hdnPan.Value <> "0,0" Then GraphSettings.Pan -= hdnPan.Value.Split(",")(IIf(ChartType = enumChartType.DepthProfile, 1, 0)) * .UnitsPerPixel
            btnZoomAll.Style("display") = IIf(hdnMouseWheel.Value & hdnPan.Value = "", "none", "normal")
        End With

        hdnMouseWheel.Value = ""
        hdnPan.Value = ""

        Dim dt As DataTable = SelectedDataTable
        If dt Is Nothing Then Exit Sub

        lblInfo.Text = String.Format(GetLocalResourceObject("lblInfoResource1.Text"), NumSelectedRecords)

        If GraphSettings.lstSeries.Count = 0 Then
            divInstructions.Visible = True
            divChart.Visible = False
            Exit Sub
        Else
            divInstructions.Visible = False
            divChart.Visible = True
        End If

        'add all selected timeseries (distinct station/pcode pairs) from selected data

        With Chart1

            .Legends.Clear()

            With .Legends.Add("WRDB")
                .LegendStyle = DataVisualization.Charting.LegendStyle.Table
                .Docking = DataVisualization.Charting.Docking.Bottom
                .Alignment = Drawing.StringAlignment.Center
                .IsEquallySpacedItems = False
                .TextWrapThreshold = 50
                .BorderColor = Drawing.Color.Black
                .BorderDashStyle = DataVisualization.Charting.ChartDashStyle.Solid
                .BorderWidth = 1
                .Font = New Drawing.Font("Tahoma", 8)
            End With

            .Width = New Unit(ChartSizes(GraphSettings.ChartSize).Width, UnitType.Pixel)
            .Height = New Unit(ChartSizes(GraphSettings.ChartSize).Height, UnitType.Pixel)

            With .ChartAreas(0)

                .BorderColor = Drawing.Color.Black
                .BorderDashStyle = DataVisualization.Charting.ChartDashStyle.Solid
                .BorderWidth = 2
                .BackColor = Drawing.Color.LightYellow

                'set up the axes 
                For axisType As DataVisualization.Charting.AxisType = DataVisualization.Charting.AxisType.Primary To DataVisualization.Charting.AxisType.Secondary
                    With Choose(axisType + 1, .AxisX, .AxisX2)
                        .TitleFont = New Drawing.Font("Tahoma", 10, Drawing.FontStyle.Bold, Drawing.GraphicsUnit.Point)
                        .MajorGrid.LineDashStyle = DataVisualization.Charting.ChartDashStyle.Dash
                        .MajorGrid.LineColor = Drawing.Color.Gray
                        .MajorTickMark.TickMarkStyle = DataVisualization.Charting.TickMarkStyle.AcrossAxis
                        .MinorGrid.LineDashStyle = DataVisualization.Charting.ChartDashStyle.Dot
                        .MinorGrid.LineColor = Drawing.Color.LightGray
                        .MinorGrid.Enabled = True
                        .MinorTickMark.TickMarkStyle = DataVisualization.Charting.TickMarkStyle.AcrossAxis
                        Dim ls As New DataVisualization.Charting.LabelStyle
                        ls.Font = New Drawing.Font("Tahoma", 8)
                        .LabelStyle = ls
                    End With
                    With Choose(axisType + 1, .AxisY, .AxisY2)
                        .TitleFont = New Drawing.Font("Tahoma", 10, Drawing.FontStyle.Bold, Drawing.GraphicsUnit.Point)
                        .MajorGrid.LineDashStyle = DataVisualization.Charting.ChartDashStyle.Dash
                        .MajorGrid.LineColor = Drawing.Color.Gray
                        .MajorTickMark.TickMarkStyle = DataVisualization.Charting.TickMarkStyle.AcrossAxis
                        .MinorGrid.LineDashStyle = DataVisualization.Charting.ChartDashStyle.Dot
                        .MinorGrid.LineColor = Drawing.Color.LightGray
                        .MinorGrid.Enabled = True
                        .MinorTickMark.TickMarkStyle = DataVisualization.Charting.TickMarkStyle.AcrossAxis
                        Dim ls As New DataVisualization.Charting.LabelStyle
                        ls.Font = New Drawing.Font("Tahoma", 8)
                        .LabelStyle = ls
                    End With
                Next

            End With

            .Titles.Clear()
            If Not String.IsNullOrEmpty(GraphSettings.Title) Then
                .Titles.Add(New DataVisualization.Charting.Title(GraphSettings.Title,
                                                                 DataVisualization.Charting.Docking.Top,
                                                                 New Drawing.Font("Tahoma", 12, Drawing.FontStyle.Bold),
                                                                 Drawing.Color.Black))
            End If

            Select Case ChartType

                Case enumChartType.TimeSeries, enumChartType.Column

                    'get unique list of station IDs
                    Dim lstSta As New Generic.List(Of String)
                    For Each series In GraphSettings.lstSeries
                        If Not lstSta.Contains(series.StationID) Then lstSta.Add(series.StationID)
                    Next
                    lstSta.Sort()

                    .Series.Clear()

                    'build y axis labels
                    For axisType As DataVisualization.Charting.AxisType = DataVisualization.Charting.AxisType.Primary To DataVisualization.Charting.AxisType.Secondary
                        Dim lstPcode As New Generic.List(Of String)
                        For Each series In GraphSettings.lstSeries
                            If series.AxisType = axisType AndAlso Not lstPcode.Contains(series.PCode) Then lstPcode.Add(series.PCode)
                        Next
                        lstPcode.Sort()
                        Title = ""
                        For Each pcode In lstPcode
                            If ProjectDataset.Tables.Contains("PCodes") Then
                                Dim dr() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode='{0}'", pcode))
                                If dr.Length = 1 Then
                                    pcode = TestNull(dr(0)("Anal_Name"), pcode)
                                    Dim units As String = TestNull(dr(0)("Units"), "")
                                    If Not String.IsNullOrEmpty(units) Then pcode &= String.Format(" ({0})", units)
                                End If
                            End If
                            If Not Title = "" Then Title &= ", "
                            Title &= pcode
                        Next
                        With Choose(axisType + 1, .ChartAreas(0).AxisY, .ChartAreas(0).AxisY2)
                            .Title = Title
                        End With
                    Next

                    For Each series In GraphSettings.lstSeries

                        'remove existing series with same name
                        If .Series.FindByName(series.Name) IsNot Nothing Then .Series.Remove(.Series.FindByName(series.Name))

                        'get sig figs in case want to label values
                        Dim sigfigs As Integer = 3
                        If ProjectDataset.Tables.Contains("PCodes") Then
                            Dim dr() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode='{0}'", series.PCode))
                            If dr.Length = 1 Then
                                sigfigs = TestNull(dr(0)("Sig_Figs"), sigfigs)
                            End If
                        End If

                        Select Case series.CalcType

                            Case enumCalcType.None

                                Dim Filter As String = String.Format("Station_ID='{0}' AND PCode='{1}'", series.StationID, series.PCode)

                                Dim ser As New DataVisualization.Charting.Series(series.Name)
                                With ser
                                    For Each dr As DataRow In dt.Select(Filter, "Date_Time")
                                        'note: will not add zero or negative points if plotting on log scale
                                        If Not IsDBNull(dr("Result")) Then
                                            If ((.XAxisType = DataVisualization.Charting.AxisType.Primary And GraphSettings.IsLogarithmicPrimary) Or
                                                (.XAxisType = DataVisualization.Charting.AxisType.Secondary And GraphSettings.IsLogarithmicSecondary)) And TestNull(dr("Result"), 0) <= 0 Then
                                                'don't plot
                                            Else
                                                .Points.AddXY(dr("Date_Time"), dr("Result"))
                                            End If
                                        End If
                                    Next

                                    If .Points.Count = 0 Then 'don't add empty series and mark for deletion
                                        series.Name = "DELETE"
                                        Continue For
                                    End If
                                    .ChartType = IIf(ChartType = enumChartType.TimeSeries, DataVisualization.Charting.SeriesChartType.Line, DataVisualization.Charting.SeriesChartType.Column)
                                    .MarkerStyle = IIf(ChartType = enumChartType.TimeSeries, DataVisualization.Charting.MarkerStyle.Circle, DataVisualization.Charting.MarkerStyle.None)
                                    .MarkerSize = 6
                                    .YAxisType = series.AxisType
                                End With
                                .Series.Add(ser)

                            Case enumCalcType.MovingAvg 'moving average on prior series data

                                Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
                                If ser Is Nothing Then Continue For
                                Dim serNew As New DataVisualization.Charting.Series(series.Name)
                                With serNew
                                    For i As Integer = 0 To ser.Points.Count - 1
                                        Dim sum As Double = 0.0
                                        Dim jmin As Integer = i - (series.CalcVal - 1) / 2
                                        Dim jmax = jmin + series.CalcVal - 1
                                        If jmin >= 0 And jmax <= ser.Points.Count - 1 Then
                                            For j As Integer = jmin To jmax
                                                sum += ser.Points(j).YValues(0)
                                            Next
                                            If ((.XAxisType = DataVisualization.Charting.AxisType.Primary And GraphSettings.IsLogarithmicPrimary) Or
                                                (.XAxisType = DataVisualization.Charting.AxisType.Secondary And GraphSettings.IsLogarithmicSecondary)) And sum <= 0 Then
                                                'don't plot
                                            Else
                                                .Points.AddXY(ser.Points(i).XValue, sum / series.CalcVal)
                                            End If
                                        End If
                                    Next
                                    .ChartType = DataVisualization.Charting.SeriesChartType.Line
                                    .YAxisType = ser.YAxisType
                                    .BorderColor = ser.BorderColor
                                    .BorderWidth = 3
                                End With
                                Chart1.Series.Add(serNew)

                            Case enumCalcType.CriteriaLimits
                                'series name is like "PCode at Sta - Max Crit"; parse to find source series and rename to remove "at Sta"
                                Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
                                If ser Is Nothing Then Continue For
                                Dim PCode As String = StringSplit(ser.Name, String.Format(" {0} ", GetGlobalResourceObject("WRDB", "at")))(0)
                                Dim Crit As String = StringSplit(series.Name, " - ")(1)
                                Dim serNew As New DataVisualization.Charting.Series(PCode & " - " & Crit)
                                With serNew

                                    If ((.XAxisType = DataVisualization.Charting.AxisType.Primary And GraphSettings.IsLogarithmicPrimary) Or
                                        (.XAxisType = DataVisualization.Charting.AxisType.Secondary And GraphSettings.IsLogarithmicSecondary)) And series.CalcVal <= 0 Then
                                        'don't plot
                                    Else
                                        .Points.AddXY(ser.Points(0).XValue, series.CalcVal)
                                        .Points.AddXY(ser.Points(ser.Points.Count - 1).XValue, series.CalcVal)
                                    End If
                                    .ChartType = DataVisualization.Charting.SeriesChartType.Line
                                    .YAxisType = ser.YAxisType
                                    .BorderWidth = 3
                                    .BorderDashStyle = DataVisualization.Charting.ChartDashStyle.Dash
                                End With
                                Chart1.Series.Add(serNew)

                        End Select

                        'show value labels if not too many points on graph
                        With Chart1.Series.Last
                            .IsValueShownAsLabel = GraphSettings.ShowValueLabels AndAlso .Points.Count <= 24
                            .LabelFormat = "N" & sigfigs
                        End With

                    Next

                    'zoom value will be positive or negative decimal; treat as ratio of min to max to set min/max value to

                    'get range based on all series
                    Dim xmin As Double = Double.MaxValue, xmax As Double = Double.MinValue
                    Dim ymin1 As Double = Double.MaxValue, ymax1 As Double = Double.MinValue
                    Dim ymin2 As Double = Double.MaxValue, ymax2 As Double = Double.MinValue
                    For Each ser In Chart1.Series
                        If ser.Points.Count > 0 Then
                            xmin = Math.Min(xmin, ser.Points(0).XValue)
                            xmax = Math.Max(xmax, ser.Points(ser.Points.Count - 1).XValue)
                            For i As Integer = 0 To ser.Points.Count - 1
                                If ser.YAxisType = DataVisualization.Charting.AxisType.Primary Then
                                    ymin1 = Math.Min(ymin1, ser.Points(i).YValues(0))
                                    ymax1 = Math.Max(ymax1, ser.Points(i).YValues(0))
                                Else
                                    ymin2 = Math.Min(ymin2, ser.Points(i).YValues(0))
                                    ymax2 = Math.Max(ymax2, ser.Points(i).YValues(0))
                                End If
                            Next
                        End If
                    Next

                    If xmin <> Double.MaxValue And xmax <> Double.MinValue Then

                        'widen the range a little
                        Dim dmin As Date = Date.FromOADate(xmin)
                        Dim dmax As Date = Date.FromOADate(xmax)
                        If xmax - xmin > 15 Then 'start/end at begining of month
                            dmin = New Date(dmin.Year, dmin.Month, 1)
                            dmax = dmax.AddMonths(1)
                            dmax = New Date(dmax.Year, dmax.Month, 1)
                        Else
                            dmin = New Date(dmin.Year, dmin.Month, dmin.Day, 0, 0, 0)
                            dmax = dmax.AddDays(1)
                            dmax = New Date(dmax.Year, dmax.Month, dmax.Day, 0, 0, 0)
                        End If

                        xmin = dmin.ToOADate
                        xmax = dmax.ToOADate

                        'reset min/max based on pan and zoom values 
                        Dim newmin As Double = xmin
                        Dim newmax As Double = xmax
                        With GraphSettings
                            If .Zoom <> 0 Or .Pan <> 0 Then
                                newmin = xmin + (xmax - xmin) * .Zoom / 2 + .Pan
                                newmax = xmax - (xmax - xmin) * .Zoom / 2 + .Pan
                                If newmin >= newmax Then Exit Sub
                            End If
                        End With
                        .ChartAreas(0).AxisX.Minimum = newmin
                        .ChartAreas(0).AxisX.Maximum = newmax
                    End If

                    With .ChartAreas(0)
                        .AxisX.Title = GetGlobalResourceObject("WRDB", "Date_Time")
                        If xmax - xmin > 2 Then
                            .AxisX.LabelStyle.Format = "d"
                        Else 'show times too
                            .AxisX.LabelStyle.Format = "g"
                        End If

                        'set format of y axes based on range of values displayed

                        .AxisY.LabelStyle.Format = "N2"
                        If ymax1 <> Double.MinValue Then
                            If ymax1 < 0.05 Then
                                .AxisY.LabelStyle.Format = "N3"
                            ElseIf ymax1 < 0.5 Then
                                .AxisY.LabelStyle.Format = "N2"
                            ElseIf ymax1 < 5 Then
                                .AxisY.LabelStyle.Format = "N1"
                            Else
                                .AxisY.LabelStyle.Format = "N0"
                            End If
                        End If

                        If GraphSettings.IsLogarithmicPrimary Then .AxisY.LabelStyle.Format = ""

                        .AxisY2.LabelStyle.Format = "N2"
                        If ymax2 <> Double.MinValue Then
                            If ymax2 < 0.05 Then
                                .AxisY2.LabelStyle.Format = "N3"
                            ElseIf ymax2 < 0.5 Then
                                .AxisY2.LabelStyle.Format = "N2"
                            ElseIf ymax2 < 5 Then
                                .AxisY2.LabelStyle.Format = "N1"
                            Else
                                .AxisY2.LabelStyle.Format = "N0"
                            End If
                        End If

                        If GraphSettings.IsLogarithmicSecondary Then .AxisY2.LabelStyle.Format = ""

                        .AxisY2.TextOrientation = DataVisualization.Charting.TextOrientation.Rotated270

                    End With

                Case enumChartType.DepthProfile

                    .Series.Clear()

                    With .ChartAreas(0)
                        'must use secondary axis to get it to plot at bottom
                        With .AxisX2
                            Dim lstPcode As New Generic.List(Of String)
                            For Each series In GraphSettings.lstSeries
                                If Not lstPcode.Contains(series.PCode) Then lstPcode.Add(series.PCode)
                            Next
                            lstPcode.Sort()
                            Title = ""
                            For Each pcode In lstPcode
                                If ProjectDataset.Tables.Contains("PCodes") Then
                                    Dim dr() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode='{0}'", pcode))
                                    If dr.Length = 1 Then
                                        pcode = TestNull(dr(0)("Anal_Name"), pcode)
                                        Dim units As String = TestNull(dr(0)("Units"), "")
                                        If Not String.IsNullOrEmpty(units) Then pcode &= String.Format(" ({0})", units)
                                    End If
                                End If
                                If Not Title = "" Then Title &= ", "
                                Title &= pcode
                            Next
                            .Title = Title
                        End With

                        With .AxisY
                            .Title = GetGlobalResourceObject("WRDB", "Depth_M")
                            .Minimum = 0
                            .LabelStyle.Format = "0"
                            .IsReversed = True
                        End With
                    End With

                    Dim xmin As Double = Double.MaxValue
                    Dim xmax As Double = Double.MinValue

                    For Each series In GraphSettings.lstSeries

                        'get sig figs in case want to label values
                        Dim sigfigs As Integer = 3
                        If ProjectDataset.Tables.Contains("PCodes") Then
                            Dim dr() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode='{0}'", series.PCode))
                            If dr.Length = 1 Then
                                sigfigs = TestNull(dr(0)("Sig_Figs"), sigfigs)
                            End If
                        End If

                        Select Case series.CalcType

                            Case enumCalcType.None
                                If series.DateTime = "" Then Exit Sub 'may get here because graph is updated before change in graphtype
                                Dim Filter As String = String.Format("Station_ID='{0}' AND PCode='{1}' AND Date_Time=#{2:MM/dd/yyyy HH:mm}# AND Depth_M IS NOT NULL", series.StationID, series.PCode, Date.Parse(series.DateTime))

                                Dim ser As New DataVisualization.Charting.Series(series.Name)
                                With ser
                                    For Each dr As DataRow In dt.Select(Filter, "Depth_M")
                                        If Not IsDBNull(dr("Result")) Then
                                            If ((.XAxisType = DataVisualization.Charting.AxisType.Primary And GraphSettings.IsLogarithmicPrimary) Or
                                                (.XAxisType = DataVisualization.Charting.AxisType.Secondary And GraphSettings.IsLogarithmicSecondary)) And
                                                dr("Result") > 0 Then
                                                .Points.AddXY(dr("Result"), dr("Depth_M"))
                                                xmin = Math.Min(xmin, dr("Result")) 'use to do manual scaling of axis
                                                xmax = Math.Max(xmax, dr("Result")) 'use to do manual scaling of axis
                                            Else
                                                .Points.AddXY(dr("Result"), dr("Depth_M"))
                                                xmin = Math.Min(xmin, dr("Result")) 'use to do manual scaling of axis
                                                xmax = Math.Max(xmax, dr("Result")) 'use to do manual scaling of axis
                                            End If
                                        End If
                                    Next
                                    If .Points.Count = 0 Then 'don't add empty series and mark for deletion
                                        series.Name = "DELETE"
                                        Continue For
                                    End If
                                    .ChartType = DataVisualization.Charting.SeriesChartType.Point
                                    .MarkerStyle = DataVisualization.Charting.MarkerStyle.Circle
                                    .MarkerSize = 6
                                    .XAxisType = DataVisualization.Charting.AxisType.Secondary
                                End With

                                'remove existing series with same name
                                If .Series.FindByName(ser.Name) IsNot Nothing Then .Series.Remove(.Series.FindByName(ser.Name))

                                .Series.Add(ser)

                            Case enumCalcType.MovingAvg
                                Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
                                If ser Is Nothing Then
                                    series.Name = "DELETE"
                                    Continue For
                                End If
                                Dim serNew As New DataVisualization.Charting.Series(series.Name)
                                With serNew
                                    For i As Integer = 0 To ser.Points.Count - 1
                                        Dim sum As Double = 0.0
                                        Dim jmin As Integer = i - (series.CalcVal - 1) / 2
                                        Dim jmax = jmin + series.CalcVal - 1
                                        If jmin >= 0 And jmax <= ser.Points.Count - 1 Then
                                            For j As Integer = jmin To jmax
                                                sum += ser.Points(j).XValue
                                            Next
                                            If ((.XAxisType = DataVisualization.Charting.AxisType.Primary And GraphSettings.IsLogarithmicPrimary) Or
                                                    (.XAxisType = DataVisualization.Charting.AxisType.Secondary And GraphSettings.IsLogarithmicSecondary)) And
                                                    sum > 0 Then
                                                .Points.AddXY(sum / series.CalcVal, ser.Points(i).YValues(0))
                                            Else
                                                .Points.AddXY(sum / series.CalcVal, ser.Points(i).YValues(0))
                                            End If
                                        End If
                                    Next
                                    .ChartType = DataVisualization.Charting.SeriesChartType.Line
                                    .XAxisType = DataVisualization.Charting.AxisType.Secondary
                                    .YAxisType = ser.YAxisType
                                    .BorderColor = ser.BorderColor
                                    .BorderWidth = 3
                                End With
                                Chart1.Series.Add(serNew)

                            Case enumCalcType.CriteriaLimits
                                Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
                                If ser Is Nothing Then Continue For
                                Dim serNew As New DataVisualization.Charting.Series(series.Name)
                                With serNew
                                    If ((.XAxisType = DataVisualization.Charting.AxisType.Primary And GraphSettings.IsLogarithmicPrimary) Or
                                        (.XAxisType = DataVisualization.Charting.AxisType.Secondary And GraphSettings.IsLogarithmicSecondary)) And
                                        series.CalcVal > 0 Then
                                        .Points.AddXY(series.CalcVal, ser.Points(0).YValues(0))
                                        .Points.AddXY(series.CalcVal, ser.Points(ser.Points.Count - 1).YValues(0))
                                    Else
                                        .Points.AddXY(series.CalcVal, ser.Points(0).YValues(0))
                                        .Points.AddXY(series.CalcVal, ser.Points(ser.Points.Count - 1).YValues(0))
                                    End If

                                    .ChartType = DataVisualization.Charting.SeriesChartType.Line
                                    .XAxisType = DataVisualization.Charting.AxisType.Secondary
                                    .YAxisType = ser.YAxisType
                                    .BorderWidth = 3
                                    .BorderDashStyle = DataVisualization.Charting.ChartDashStyle.Dash
                                End With
                                xmax = Math.Max(xmax, series.CalcVal)
                                Chart1.Series.Add(serNew)

                        End Select

                        'show value labels if not too many points on graph
                        With Chart1.Series.Last
                            .IsValueShownAsLabel = GraphSettings.ShowValueLabels AndAlso .Points.Count <= 24
                            .LabelFormat = "N" & sigfigs
                        End With

                    Next

                    'I don't like auto-scaling here, so do override
                    With .ChartAreas(0).AxisX2
                        If GraphSettings.IsLogarithmicPrimary Then
                            .Minimum = 10 ^ Math.Floor(Math.Log10(xmin))
                            .Maximum = 10 ^ Math.Ceiling(Math.Log10(xmax))
                        Else
                            Dim incr As Double = 10 ^ Math.Floor(Math.Log10(xmax)) 'for 1<=x<100->1; 100<=x<1000->10, etc.
                            If xmin < 0 Then
                                .Minimum = Math.Floor(xmin / incr) * incr 'round to next lower increment
                            Else
                                .Minimum = 0
                            End If
                            .Maximum = Math.Ceiling(xmax / incr) * incr 'round to next higher increment
                        End If
                    End With

                    'allow panning and zooming on y axis

                    'get range based on all series
                    Dim min As Double = 0.0, max As Double = Double.MinValue
                    For Each ser In Chart1.Series
                        If ser.Points.Count > 0 Then
                            max = Math.Max(max, ser.Points(ser.Points.Count - 1).YValues(0))
                        End If
                    Next

                    If max <> Double.MinValue Then

                        'widen the range a little (next highest 10 meters)
                        max = Math.Ceiling(max / 10.0) * 10.0

                        'reset min/max based on pan and zoom values 
                        Dim newmin As Double = min
                        Dim newmax As Double = max
                        With GraphSettings
                            If .Zoom <> 0 Or .Pan <> 0 Then
                                newmin = min + (max - min) * .Zoom / 2 + .Pan
                                newmax = max - (max - min) * .Zoom / 2 + .Pan
                                If newmin < 0 Then newmin = 0
                                If newmin >= newmax Then Exit Sub
                            End If
                        End With
                        .ChartAreas(0).AxisY.Minimum = newmin
                        .ChartAreas(0).AxisY.Maximum = newmax
                    End If

            End Select

        End With

        'delete all series that had no data points
        For i As Integer = GraphSettings.lstSeries.Count - 1 To 0 Step -1
            If GraphSettings.lstSeries(i).Name = "DELETE" Then GraphSettings.lstSeries.RemoveAt(i)
        Next

        'fix log axis; can only do so if at least one series with non-zero values on that axis
        Dim numPrimary As Integer = 0
        Dim numSecondary As Integer = 0

        Select Case ChartType
            Case enumChartType.TimeSeries
                For Each ser In Chart1.Series
                    If ser.YAxisType = DataVisualization.Charting.AxisType.Primary Then numPrimary += 1 Else numSecondary += 1
                Next
                Chart1.ChartAreas(0).AxisY.IsLogarithmic = GraphSettings.IsLogarithmicPrimary AndAlso numPrimary > 0
                Chart1.ChartAreas(0).AxisY2.IsLogarithmic = GraphSettings.IsLogarithmicSecondary AndAlso numSecondary > 0
            Case enumChartType.DepthProfile
                Chart1.ChartAreas(0).AxisX2.IsLogarithmic = GraphSettings.IsLogarithmicPrimary AndAlso Chart1.Series.Count > 0
        End Select

        GraphSettings.Save()

        'FillSeriesList()

    End Sub

    Protected Sub imgChartSize_Click(sender As Object, e As ImageMapEventArgs) Handles imgChartSize.Click
        If GraphSettings Is Nothing Then Response.Redirect("Configure.aspx") 'if session terminates or website restarts; goto configure screen
        With GraphSettings
            Select Case e.PostBackValue
                Case "Small" : .ChartSize = enumChartSize.Small
                Case "Medium" : .ChartSize = enumChartSize.Medium
                Case "Large" : .ChartSize = enumChartSize.Large
            End Select
            .Zoom = 0
            .Pan = 0
            .Save()
        End With
        RenderChart()
    End Sub

    Private Sub btnOptions_Click(sender As Object, e As EventArgs) Handles btnOptions.Click
        FillSeriesList()
        ShowDialog(UpdChart, pnlOptions, "Graph Options", 800)
    End Sub

    Private Sub btnOKOptions_Click(sender As Object, e As EventArgs) Handles btnOKOptions.Click

        If GraphSettings Is Nothing Then Response.Redirect("Configure.aspx") 'if session terminates or website restarts; goto configure screen

        'graph title
        GraphSettings.Title = txtTitle.Text

        'calc series
        If lstCalc.SelectedIndex <> -1 And lstCalcType.SelectedIndex > 0 Then
            Dim ser As clsSeries = GraphSettings.lstSeries(lstCalc.SelectedIndex)
            If IsNumeric(lstCalcType.SelectedItem.Value) Then 'is moving average
                GraphSettings.lstSeries.Add(New clsSeries With {.Name = ser.Name & " - MA" & lstCalcType.SelectedValue,
                                                                .CalcType = enumCalcType.MovingAvg,
                                                                .CalcVal = lstCalcType.SelectedValue,
                                                                .CalcSource = ser.Name})
            ElseIf lstCalcType.SelectedItem.Value = "Crit" Then 'criteria limits
                Dim PCode As String = StringSplit(ser.Name, String.Format(" {0} ", GetGlobalResourceObject("WRDB", "at")))(0)
                Dim dr() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode='{0}'", PCode))
                For i As Integer = 1 To 2
                    Dim minmax As String = Choose(i, "Min", "Max")
                    Dim limit As Double = TestNull(dr(0)(minmax & "_Criteria"), Double.MinValue)
                    If limit <> Double.MinValue And limit <> 0.0 Then
                        GraphSettings.lstSeries.Add(New clsSeries With {.Name = ser.Name & " - " & minmax & " Crit",
                                                                        .CalcType = enumCalcType.CriteriaLimits,
                                                                        .CalcVal = limit,
                                                                        .CalcSource = ser.Name})
                    End If
                Next
            End If
        End If

        'delete series
        For i As Integer = lstDelete.Items.Count - 1 To 0 Step -1
            If lstDelete.Items(i).Selected Then
                GraphSettings.lstSeries.RemoveAt(i)
            End If
        Next

        'point value labels

        GraphSettings.ShowValueLabels = chkShowValueLabels.Checked

        'log axes
        GraphSettings.IsLogarithmicPrimary = chkLogAxisPrimary.Checked
        GraphSettings.IsLogarithmicSecondary = chkLogAxisSecondary.Checked()

        GraphSettings.Save()

        RenderChart()
    End Sub

    ''' <summary>
    ''' This PageMethod allows a resource value to be passed to the page so JavaScript can display message in correct language
    ''' </summary>
    <System.Web.Services.WebMethod()>
    Public Shared Function GetResource(key As String) As String
        Dim res As String = HttpContext.GetGlobalResourceObject("WRDB", key, ProjectSettings.Language)
        If String.IsNullOrEmpty(res) Then Throw New ApplicationException("Resource was not found: " & key) Else Return res
    End Function

    'note: the following approach could be used to implement the JavaScript plotting library called jqplot
    'I started to implement, but did not complete. The only advantage to this library is that zooming would be
    'much faster, but jqplot does not support panning.

    'I don't think it is worth the effort because the Microsoft plots look very good

    ' ''' <summary>
    ' ''' This PageMethod is used to return data series information to JQPlot
    ' ''' </summary>
    '<System.Web.Services.WebMethod()>
    'Public Shared Function GetJQPlot(ChartType As Integer, ByRef DataSeries As String, ByRef PlotOptions As String) As Boolean
    ''must return an array where each element is an array of pairs of x,y data for a series
    'Dim sbSeries As New StringBuilder
    'Dim sbOptions As New StringBuilder

    'Dim Title As String = ""

    'Select Case ChartType

    '    Case enumChartType.TimeSeries

    '        'get unique list of station IDs
    '        Dim lstSta As New Generic.List(Of String)
    '        For Each series In GraphSettings.lstSeries
    '            If Not lstSta.Contains(series.StationID) Then lstSta.Add(series.StationID)
    '        Next
    '        lstSta.Sort()

    '        sbSeries.Clear()

    '        sbOptions.Append("{axes: {")

    '        'build y axis labels
    '        For axisType As DataVisualization.Charting.AxisType = DataVisualization.Charting.AxisType.Primary To DataVisualization.Charting.AxisType.Secondary
    '            Dim lstPcode As New Generic.List(Of String)
    '            For Each series In GraphSettings.lstSeries
    '                If series.AxisType = axisType AndAlso Not lstPcode.Contains(series.PCode) Then lstPcode.Add(series.PCode)
    '            Next
    '            lstPcode.Sort()
    '            Title = ""
    '            For Each pcode In lstPcode
    '                If ProjectDataset.Tables.Contains("PCodes") Then
    '                    Dim dr() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode='{0}'", pcode))
    '                    If dr.Length = 1 Then
    '                        pcode = TestNull(dr(0)("Anal_Name"), pcode)
    '                        Dim units As String = TestNull(dr(0)("Units"), "")
    '                        If Not String.IsNullOrEmpty(units) Then pcode &= String.Format(" ({0})", units)
    '                    End If
    '                End If
    '                If Not Title = "" Then Title &= ", "
    '                Title &= pcode
    '            Next
    '            sbOptions.Append(Choose(axisType + 1, "yaxis", "y2axis") & ": {label:" & Title & "}")
    '        Next

    '        For Each series In GraphSettings.lstSeries

    '            'remove existing series with same name
    '            If .Series.FindByName(series.Name) IsNot Nothing Then .Series.Remove(.Series.FindByName(series.Name))

    '            Select Case series.CalcType

    '                Case enumCalcType.None

    '                    Dim Filter As String = String.Format("Station_ID='{0}' AND PCode='{1}'", series.StationID, series.PCode)

    '                    Dim ser As New DataVisualization.Charting.Series(series.Name)
    '                    With ser
    '                        For Each dr As DataRow In dt.Select(Filter, "Date_Time")
    '                            .Points.AddXY(dr("Date_Time"), dr("Result"))
    '                        Next

    '                        If .Points.Count = 0 Then 'don't add empty series and mark for deletion
    '                            series.Name = "DELETE"
    '                            Continue For
    '                        End If
    '                        .ChartType = DataVisualization.Charting.SeriesChartType.Line
    '                        .MarkerStyle = DataVisualization.Charting.MarkerStyle.Circle
    '                        .MarkerSize = 6
    '                        .YAxisType = series.AxisType
    '                    End With
    '                    .Series.Add(ser)

    '                Case enumCalcType.MovingAvg 'moving average on prior series data

    '                    Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
    '                    If ser Is Nothing Then Continue For
    '                    Dim serNew As New DataVisualization.Charting.Series(series.Name)
    '                    With serNew
    '                        For i As Integer = 0 To ser.Points.Count - 1
    '                            Dim sum As Double = 0.0
    '                            Dim jmin As Integer = i - (series.CalcVal - 1) / 2
    '                            Dim jmax = jmin + series.CalcVal - 1
    '                            If jmin >= 0 And jmax <= ser.Points.Count - 1 Then
    '                                For j As Integer = jmin To jmax
    '                                    sum += ser.Points(j).YValues(0)
    '                                Next
    '                                .Points.AddXY(ser.Points(i).XValue, sum / series.CalcVal)
    '                            End If
    '                        Next
    '                        .ChartType = DataVisualization.Charting.SeriesChartType.Line
    '                        .YAxisType = ser.YAxisType
    '                        .BorderColor = ser.BorderColor
    '                        .BorderWidth = 3
    '                    End With
    '                    Chart1.Series.Add(serNew)

    '                Case enumCalcType.CriteriaLimits
    '                    'series name is like "PCode at Sta - Max Crit"; parse to find source series and rename to remove "at Sta"
    '                    Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
    '                    If ser Is Nothing Then Continue For
    '                    Dim PCode As String = StringSplit(ser.Name, String.Format(" {0} ", GetGlobalResourceObject("WRDB", "at")))(0)
    '                    Dim Crit As String = StringSplit(series.Name, " - ")(1)
    '                    Dim serNew As New DataVisualization.Charting.Series(PCode & " - " & Crit)
    '                    With serNew
    '                        .Points.AddXY(ser.Points(0).XValue, series.CalcVal)
    '                        .Points.AddXY(ser.Points(ser.Points.Count - 1).XValue, series.CalcVal)
    '                        .ChartType = DataVisualization.Charting.SeriesChartType.Line
    '                        .YAxisType = ser.YAxisType
    '                        .BorderWidth = 3
    '                        .BorderDashStyle = DataVisualization.Charting.ChartDashStyle.Dash
    '                    End With
    '                    Chart1.Series.Add(serNew)

    '            End Select

    '        Next

    '        'zoom value will be positive or negative decimal; treat as ratio of min to max to set min/max value to

    '        'get range based on all series
    '        Dim xmin As Double = Double.MaxValue, xmax As Double = Double.MinValue
    '        Dim ymin1 As Double = Double.MaxValue, ymax1 As Double = Double.MinValue
    '        Dim ymin2 As Double = Double.MaxValue, ymax2 As Double = Double.MinValue
    '        For Each ser In Chart1.Series
    '            If ser.Points.Count > 0 Then
    '                xmin = Math.Min(xmin, ser.Points(0).XValue)
    '                xmax = Math.Max(xmax, ser.Points(ser.Points.Count - 1).XValue)
    '                If ser.YAxisType = DataVisualization.Charting.AxisType.Primary Then
    '                    ymin1 = Math.Min(ymin1, ser.Points(0).YValues(0))
    '                    ymax1 = Math.Max(ymax1, ser.Points(0).YValues(0))
    '                Else
    '                    ymin2 = Math.Min(ymin2, ser.Points(0).YValues(0))
    '                    ymax2 = Math.Max(ymax2, ser.Points(0).YValues(0))
    '                End If
    '            End If
    '        Next

    '        If xmin <> Double.MaxValue And xmax <> Double.MinValue Then

    '            'widen the range a little
    '            Dim dmin As Date = Date.FromOADate(xmin)
    '            Dim dmax As Date = Date.FromOADate(xmax)
    '            If xmax - xmin > 15 Then 'start/end at begining of month
    '                dmin = New Date(dmin.Year, dmin.Month, 1)
    '                dmax = dmax.AddDays(1)
    '                dmax = New Date(dmax.Year, dmax.Month, 1)
    '            Else
    '                dmin = New Date(dmin.Year, dmin.Month, dmin.Day, 0, 0, 0)
    '                dmax = dmax.AddDays(1)
    '                dmax = New Date(dmax.Year, dmax.Month, dmax.Day, 0, 0, 0)
    '            End If

    '            xmin = dmin.ToOADate
    '            xmax = dmax.ToOADate

    '            'reset min/max based on pan and zoom values 
    '            Dim newmin As Double = xmin
    '            Dim newmax As Double = xmax
    '            With GraphSettings
    '                If .Zoom <> 0 Or .Pan <> 0 Then
    '                    newmin = xmin + (xmax - xmin) * .Zoom / 2 + .Pan
    '                    newmax = xmax - (xmax - xmin) * .Zoom / 2 + .Pan
    '                    If newmin >= newmax Then Exit Function
    '                End If
    '            End With
    '            .ChartAreas(0).AxisX.Minimum = newmin
    '            .ChartAreas(0).AxisX.Maximum = newmax
    '        End If

    '        With .ChartAreas(0)
    '            .AxisX.Title = GetGlobalResourceObject("WRDB", "Date_Time")

    '            'set format of y axes based on range of values displayed

    '            .AxisY.LabelStyle.Format = "0.00"
    '            If ymax1 <> Double.MinValue Then
    '                If ymax1 < 0.05 Then
    '                    .AxisY.LabelStyle.Format = "0.000"
    '                ElseIf ymax1 < 0.5 Then
    '                    .AxisY.LabelStyle.Format = "0.00"
    '                ElseIf ymax1 < 5 Then
    '                    .AxisY.LabelStyle.Format = "0.0"
    '                Else
    '                    .AxisY.LabelStyle.Format = "0"
    '                End If
    '            End If

    '            .AxisY2.LabelStyle.Format = "0.00"
    '            If ymax2 <> Double.MinValue Then
    '                If ymax2 < 0.05 Then
    '                    .AxisY2.LabelStyle.Format = "0.000"
    '                ElseIf ymax2 < 0.5 Then
    '                    .AxisY2.LabelStyle.Format = "0.00"
    '                ElseIf ymax2 < 5 Then
    '                    .AxisY2.LabelStyle.Format = "0.0"
    '                Else
    '                    .AxisY2.LabelStyle.Format = "0"
    '                End If
    '            End If
    '            .AxisY2.TextOrientation = DataVisualization.Charting.TextOrientation.Rotated270

    '        End With

    '    Case enumChartType.DepthProfile

    '        .Series.Clear()

    '        With .ChartAreas(0)
    '            'must use secondary axis to get it to plot at bottom
    '            With .AxisX2
    '                Dim lstPcode As New Generic.List(Of String)
    '                For Each series In GraphSettings.lstSeries
    '                    If Not lstPcode.Contains(series.PCode) Then lstPcode.Add(series.PCode)
    '                Next
    '                lstPcode.Sort()
    '                Title = ""
    '                For Each pcode In lstPcode
    '                    If ProjectDataset.Tables.Contains("PCodes") Then
    '                        Dim dr() As DataRow = ProjectDataset.Tables("PCodes").Select(String.Format("PCode='{0}'", pcode))
    '                        If dr.Length = 1 Then
    '                            pcode = TestNull(dr(0)("Anal_Name"), pcode)
    '                            Dim units As String = TestNull(dr(0)("Units"), "")
    '                            If Not String.IsNullOrEmpty(units) Then pcode &= String.Format(" ({0})", units)
    '                        End If
    '                    End If
    '                    If Not Title = "" Then Title &= ", "
    '                    Title &= pcode
    '                Next
    '                .Title = Title
    '            End With

    '            With .AxisY
    '                .Title = GetGlobalResourceObject("WRDB", "Depth_M")
    '                .Minimum = 0
    '                .LabelStyle.Format = "0"
    '                .IsReversed = True
    '            End With
    '        End With

    '        Dim xmin As Double = Double.MaxValue
    '        Dim xmax As Double = Double.MinValue

    '        For Each series In GraphSettings.lstSeries
    '            Select Case series.CalcType

    '                Case enumCalcType.None
    '                    Dim Filter As String = String.Format("Station_ID='{0}' AND PCode='{1}' AND Date_Time={2} AND Depth_M IS NOT NULL", series.StationID, series.PCode, Project.DB.DateTime(Date.Parse(series.DateTime)))

    '                    Dim ser As New DataVisualization.Charting.Series(series.Name)
    '                    With ser
    '                        For Each dr As DataRow In dt.Select(Filter, "Depth_M")
    '                            .Points.AddXY(dr("Result"), dr("Depth_M"))
    '                            xmin = Math.Min(xmin, dr("Result")) 'use to do manual scaling of axis
    '                            xmax = Math.Max(xmax, dr("Result")) 'use to do manual scaling of axis
    '                        Next
    '                        If .Points.Count = 0 Then 'don't add empty series and mark for deletion
    '                            series.Name = "DELETE"
    '                            Continue For
    '                        End If
    '                        .ChartType = DataVisualization.Charting.SeriesChartType.Point
    '                        .MarkerStyle = DataVisualization.Charting.MarkerStyle.Circle
    '                        .MarkerSize = 6
    '                        .XAxisType = DataVisualization.Charting.AxisType.Secondary
    '                    End With

    '                    'remove existing series with same name
    '                    If .Series.FindByName(ser.Name) IsNot Nothing Then .Series.Remove(.Series.FindByName(ser.Name))

    '                    .Series.Add(ser)

    '                Case enumCalcType.MovingAvg
    '                    Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
    '                    If ser Is Nothing Then
    '                        series.Name = "DELETE"
    '                        Continue For
    '                    End If
    '                    Dim serNew As New DataVisualization.Charting.Series(series.Name)
    '                    With serNew
    '                        For i As Integer = 0 To ser.Points.Count - 1
    '                            Dim sum As Double = 0.0
    '                            Dim jmin As Integer = i - (series.CalcVal - 1) / 2
    '                            Dim jmax = jmin + series.CalcVal - 1
    '                            If jmin >= 0 And jmax <= ser.Points.Count - 1 Then
    '                                For j As Integer = jmin To jmax
    '                                    sum += ser.Points(j).XValue
    '                                Next
    '                                .Points.AddXY(sum / series.CalcVal, ser.Points(i).YValues(0))
    '                            End If
    '                        Next
    '                        .ChartType = DataVisualization.Charting.SeriesChartType.Line
    '                        .XAxisType = DataVisualization.Charting.AxisType.Secondary
    '                        .YAxisType = ser.YAxisType
    '                        .BorderColor = ser.BorderColor
    '                        .BorderWidth = 3
    '                    End With
    '                    Chart1.Series.Add(serNew)

    '                Case enumCalcType.CriteriaLimits
    '                    Dim ser As DataVisualization.Charting.Series = .Series.FindByName(StringSplit(series.Name, " - ")(0))
    '                    If ser Is Nothing Then Continue For
    '                    Dim serNew As New DataVisualization.Charting.Series(series.Name)
    '                    With serNew
    '                        .Points.AddXY(series.CalcVal, ser.Points(0).YValues(0))
    '                        .Points.AddXY(series.CalcVal, ser.Points(ser.Points.Count - 1).YValues(0))
    '                        .ChartType = DataVisualization.Charting.SeriesChartType.Line
    '                        .XAxisType = DataVisualization.Charting.AxisType.Secondary
    '                        .YAxisType = ser.YAxisType
    '                        .BorderWidth = 3
    '                        .BorderDashStyle = DataVisualization.Charting.ChartDashStyle.Dash
    '                    End With
    '                    xmax = Math.Max(xmax, series.CalcVal)
    '                    Chart1.Series.Add(serNew)

    '            End Select

    '        Next

    '        'what happens if there are negative values...
    '        If xmin <= 0 Then GraphSettings.IsLogarithmic = False

    '        'I don't like auto-scaling here, so do override
    '        With .ChartAreas(0).AxisX2
    '            If GraphSettings.IsLogarithmic Then
    '                .Minimum = 10 ^ Math.Floor(Math.Log10(xmin))
    '                .Maximum = 10 ^ Math.Ceiling(Math.Log10(xmax))
    '            Else
    '                Dim incr As Double = 10 ^ Math.Floor(Math.Log10(xmax)) 'for 1<=x<100->1; 100<=x<1000->10, etc.
    '                If xmin < 0 Then
    '                    .Minimum = Math.Floor(xmin / incr) * incr 'round to next lower increment
    '                Else
    '                    .Minimum = 0
    '                End If
    '                .Maximum = Math.Ceiling(xmax / incr) * incr 'round to next higher increment
    '            End If
    '        End With

    '        'allow panning and zooming on y axis

    '        'get range based on all series
    '        Dim min As Double = 0.0, max As Double = Double.MinValue
    '        For Each ser In Chart1.Series
    '            If ser.Points.Count > 0 Then
    '                max = Math.Max(max, ser.Points(ser.Points.Count - 1).YValues(0))
    '            End If
    '        Next

    '        If max <> Double.MinValue Then

    '            'widen the range a little (next highest 10 meters)
    '            max = Math.Ceiling(max / 10.0) * 10.0

    '            'reset min/max based on pan and zoom values 
    '            Dim newmin As Double = min
    '            Dim newmax As Double = max
    '            With GraphSettings
    '                If .Zoom <> 0 Or .Pan <> 0 Then
    '                    newmin = min + (max - min) * .Zoom / 2 + .Pan
    '                    newmax = max - (max - min) * .Zoom / 2 + .Pan
    '                    If newmin < 0 Then newmin = 0
    '                    If newmin >= newmax Then Exit Function
    '                End If
    '            End With
    '            .ChartAreas(0).AxisY.Minimum = newmin
    '            .ChartAreas(0).AxisY.Maximum = newmax
    '        End If

    'End Select

    'End Function

    Private Sub Chart1_PostPaint(sender As Object, e As DataVisualization.Charting.ChartPaintEventArgs) Handles Chart1.PostPaint
        'need to get the scale of the x axis in case will pan by dragging the mouse
        With Chart1.ChartAreas(0)
            Dim axis As DataVisualization.Charting.Axis = Choose(GraphSettings.ChartType + 1, .AxisX, .AxisX, .AxisY)
            With axis
                GraphSettings.UnitsPerPixel = (.Maximum - .Minimum) / (.ValueToPixelPosition(.Maximum) - .ValueToPixelPosition(.Minimum))
                GraphSettings.Save()
            End With
        End With
    End Sub

    Private Sub btnZoomAll_Click(sender As Object, e As EventArgs) Handles btnZoomAll.Click
        With GraphSettings
            .Zoom = 0.0
            .Pan = 0.0
            RenderChart()
        End With
    End Sub

End Class